<template>
  <div class="changePsd">
    <!-- 修改密码 -->
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="原密码">
        <el-input size="small" placeholder="请输入原密码" v-model="form.d" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码">
        <el-input size="small" placeholder="请输入新密码" v-model="form.xinpwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="重复密码">
        <el-input
          size="small"
          placeholder="请再次输入新密码"
          v-model="form.con"
          show-password
          @keyup.enter.native="handleSave"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button style="padding: 5px 30px" size="small" type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        d: "",
        xinpwd: "",
        con: ""
      },
      // 身份令牌
      myToken: ""
    };
  },
  methods: {
    handleSave() {
      // 获取令牌
      this.myToken = sessionStorage.getItem("myToken");
      // 验证数字字母和特殊字符
      const pwdPatrn = /^[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、0-9A-Za-z]{6,}$/;
      // 正则验证密码，不能为空，长度要大于六位数，不能中文，重置密码要一致
      if (!pwdPatrn.test(this.form.d)) {
        if (this.form.d === "") {
          this.$message.error("密码不能为空");
          return;
        }
        this.$message.error("密码格式错误");
        return;
      } else if (!pwdPatrn.test(this.form.xinpwd)) {
        if (this.form.xinpwd === "") {
          this.$message.error("新密码不能为空");
          return;
        }
        this.$message.error("密码格式错误");
        return;
      } else if (this.form.xinpwd == this.form.d) {
        this.$message.error("新旧密码重复");
        return;
      } else if (this.form.xinpwd !== this.form.con) {
        this.$message.error("前后两次密码不一致");
        return;
      } else {
        // console.log(JSON.stringify(this.form));
        var fileData = new FormData();
        fileData.append("d", this.form.d);
        fileData.append("xinpwd", this.form.xinpwd);
        fileData.append("con", this.form.con);
        // 发送请求
        this.$api.changePassword(fileData, this.myToken).then(res => {
          const { succeed, errmsg } = res;
          if (succeed) {
            this.$message({
              message: "密码修改成功",
              type: "success"
            });
          } else {
            this.$message.error(errmsg);
          }
        });
      }
    }
  }
};
</script>

<style lang="less" scoped>
@deep: ~">>>";
.changePsd {
  background-color: #fff;
  padding: 20px 50px;
}
// 修改表单中内容部分的宽度
.changePsd @{deep} .el-input {
  width: 400px;
}
// 修改表单中提供的操作的宽度
.changePsd @{deep} .el-upload-list--picture {
  width: 400px;
}
// 修改表单的样式
.changePsd @{deep} .el-form {
  padding: 30px 30%;
  box-sizing: border-box;
}
// 修改表单中输入框的宽度
.changePsd @{deep} .el-input__inner {
  width: 400px;
}
</style>
